from datetime import datetime

from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Float, DateTime

# 创建数据库引擎
engine = create_engine('sqlite:///db.db', echo=True)


def create_dynamic_table(table_name, columns):
    """
    动态创建数据库表
    :param table_name: 表名
    :param columns: 字段及其类型的字典，格式为 {'字段名': 类型}
    """
    meta = MetaData()
    # 创建表对象
    table = Table(table_name, meta)
    table.append_column(Column('id', Integer, primary_key=True, autoincrement=True))
    table.append_column(Column('创建时间', DateTime, default=datetime.now))
    # 根据传入的字段及类型动态添加列
    for column_name, column_type in columns.items():
        if column_type == 'Integer':
            column = Column(column_name, Integer)
        elif column_type == 'String':
            column = Column(column_name, String)
        elif column_type == 'Float':
            column = Column(column_name, Float)
        else:
            raise ValueError(f"不支持的字段类型: {column_type}")

        table.append_column(column)

    # 创建表
    meta.create_all(engine)



